﻿using Calligraphy.Common;
using Calligraphy.DataModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Search;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Grid App template is documented at http://go.microsoft.com/fwlink/?LinkId=234226

namespace Calligraphy
{
    /// <summary>
    /// 提供特定于应用程序的行为，以补充默认的应用程序类。
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton Application object.  This is the first line of authored code
        /// 逻辑上等同于 main() 或 WinMain()。
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
        protected override void OnWindowCreated(WindowCreatedEventArgs args)
        {
            Windows.ApplicationModel.Search.SearchPane searchPane = SearchPane.GetForCurrentView();
            searchPane.QuerySubmitted += new TypedEventHandler<Windows.ApplicationModel.Search.SearchPane, Windows.ApplicationModel.Search.SearchPaneQuerySubmittedEventArgs>(OnQuerySubmitted);
        }
        /// <summary>
        /// 在应用程序由最终用户正常启动时进行调用。
        /// 当启动应用程序以执行打开特定的文件或显示搜索结果等操作时
        /// 将使用其他入口点。
        /// </summary>
        /// <param name="args">有关启动请求和过程的详细信息。</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            // Do not repeat app initialization when already running, just ensure that
            // the window is active
            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                Window.Current.Activate();
                return;
            }

            // Create a Frame to act as the navigation context and associate it with
            // a SuspensionManager key
            var rootFrame = new Frame();
            SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                // Restore the saved session state only when appropriate
                await SuspensionManager.RestoreAsync();
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // 并通过将所需信息作为导航参数传入来配置
                // 参数
                if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups"))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            // 将 Frame 放置在当前窗口中并确保其处于活动状态
            Window.Current.Content = rootFrame;
            Window.Current.Activate();
        }

        /// <summary>
        /// 在将要挂起应用程序执行时调用。在不知道应用程序
        /// 将被终止还是恢复的情况下保存应用程序状态，
        /// 并让内存内容保持不变。
        /// </summary>
        /// <param name="sender">挂起的请求的源。</param>
        /// <param name="e">有关挂起的请求的详细信息。</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await SuspensionManager.SaveAsync();
            deferral.Complete();
        }

        /// <summary>
        /// 在激活应用程序以显示搜索结果时调用。
        /// </summary>
        /// <param name="args">有关激活请求的详细信息。</param>
        protected async override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
        {
            // TODO: 在 OnWindowCreated 中注册 Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().QuerySubmitted
            // 事件，以在应用程序运行后加快搜索

            // 如果窗口尚未使用框架导航，则插入我们自己的框架
            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;

            // 如果应用程序不包含顶级框架，则可能表示这是
            // 初次启动应用程序。一般而言，此方法和 App.xaml.cs 中的 OnLaunched 
            // 可调用公共方法。
            if (frame == null)
            {
                // 创建要充当导航上下文的框架，并将其与
                // SuspensionManager 键关联
                frame = new Frame();
                Calligraphy.Common.SuspensionManager.RegisterFrame(frame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // 仅当适用时还原保存的会话状态
                    try
                    {
                        await Calligraphy.Common.SuspensionManager.RestoreAsync();
                    }
                    catch (Exception)
                    {
                        //还原状态时出现问题。
                        //假定没有状态并继续
                    }
                }
            }

            frame.Navigate(typeof(SearchResultsPage1), args.QueryText);
            Window.Current.Content = frame;

            // 确保当前窗口处于活动状态
            Window.Current.Activate();
        }
        

        private  void OnQuerySubmitted(Windows.ApplicationModel.Search.SearchPane sender, Windows.ApplicationModel.Search.SearchPaneQuerySubmittedEventArgs args)
        {
            SearchResultSource srs = new SearchResultSource();
            //srs.SearchPhoto(args.QueryText);
            var frame = Window.Current.Content as Frame;
            frame.Navigate(typeof(SearchResultsPage1), args.QueryText);
            Window.Current.Content = frame;
            //Window.Current.Activate();
            
        }
    }
}
